<?php
// ========================== 文件说明 ==========================//
// 本文件说明：数据管理
// --------------------------------------------------------------//
// 本程序作者：angel
// --------------------------------------------------------------//
// 本程序版本：SaBlog-X Ver 1.6
// --------------------------------------------------------------//
// 本程序主页：http://www.sablog.net
// ========================== 开发环境 ==========================//
// register_globals = Off
// --------------------------------------------------------------//
// magic_quotes_gpc = On
// --------------------------------------------------------------//
// safe_mode = On
// --------------------------------------------------------------//
// Windows server 2003 & Linux & FreeBSD
// --------------------------------------------------------------//
// Apache/1.3.33 & PHP/4.3.2 & MySQL/4.0.17
// --------------------------------------------------------------//
// Apache/1.3.34 & PHP/4.4.1 & MySQL/5.0.16
// --------------------------------------------------------------//
// Apache/2.0.55 & PHP/5.1.1 & MySQL/5.0.15
// --------------------------------------------------------------//
// Copyright (C) Security Angel Team All Rights Reserved.
// ==============================================================//

if(!defined('SABLOG_ROOT') || !isset($php_self) || !preg_match("/[\/\\\\]cp\.php$/", $php_self)) {
	exit('Access Denied');
}

//权限检查
permission();

!$action && $action = 'mysqlinfo';

$backupdir = 'cache/backupdata';

$tables = array(
	$db_prefix.'articles',
	$db_prefix.'attachments',
	$db_prefix.'categories',
	$db_prefix.'comments',
	$db_prefix.'links',
	$db_prefix.'searchindex',
	$db_prefix.'settings',
	$db_prefix.'sessions',
	$db_prefix.'statistics',
	$db_prefix.'stylevars',
	$db_prefix.'tags',
	$db_prefix.'trackbacklog',
	$db_prefix.'trackbacks',
	$db_prefix.'users'
);

if (in_array($action, array('resume','checkresume')) && !$dbimport) {
	redirect('不允许在后台恢复数据', 'cp.php?job=tools&action=filelist');
}

if ($action == 'delsearchlog') {
	$DB->unbuffered_query("TRUNCATE TABLE {$db_prefix}searchindex");
	redirect('搜索记录已经清空', $url);
}

// 恢复数据库文件
if ($action == 'resume' && $dbimport) {
	$sqlfile = $_GET['sqlfile'] ? $_GET['sqlfile'] : $_POST['sqlfile'];
	$file = $backupdir.'/'.$sqlfile;
	$path_parts = pathinfo($file);
	if (strtolower($path_parts['extension']) != 'sql') {
		redirect('只能恢复SQL文件!','cp.php?job=tools&action=filelist');
	}
	if(@$fp = fopen($file, 'rb')) {
		$sqldump = fgets($fp, 256);
		$identify = explode(',', base64_decode(preg_replace("/^# Identify:\s*(\w+).*/s", "\\1", $sqldump)));
		$sqldump .= fread($fp, filesize($file));
		fclose($fp);
	} else {
		if($autoimport) {
			restats();
			redirect('分卷数据成功导入数据库','cp.php?job=tools&action=filelist');
		} else {
			redirect('分卷数据导入数据库失败','cp.php?job=tools&action=filelist');
		}
	}

	if($identify[0] && $identify[1] == $SABLOG_VERSION && $identify[2]) {
		$sqlquery = splitsql($sqldump);
		unset($sqldump);
		foreach($sqlquery as $sql) {
			if(trim($sql) != '') {
				$DB->query($sql, 'SILENT');
			}
		}

		$file_next = basename(preg_replace("/_($identify[2])(\..+)$/", "_".($identify[2] + 1)."\\2", $file));

		if($identify[2] == 1) {
			redirect('分卷数据成功导入数据库,程序将自动导入本次其他的备份.','cp.php?job=tools&action=resume&sqlfile='.rawurlencode($file_next).'&autoimport=yes');
		} elseif($autoimport) {
			redirect('数据文件卷号 '.$identify[2].' 成功导入，程序将自动继续。', 'cp.php?job=tools&action=resume&sqlfile='.rawurlencode($file_next).'&autoimport=yes');
		} else {
			restats();
			redirect('数据成功导入','cp.php?job=tools&action=filelist');
		}
	} else {
		redirect('数据文件非 Sablog-X 格式或与程序当前版本信息不符,无法导入.','cp.php?job=tools&action=filelist',5);
	}
}

// 备份操作
if ($action == 'dobackup') {
	$volume = intval($volume) + 1;
	$sqlfilename = SABLOG_ROOT.$backupdir.'/'.$filename.'_'.$volume.'.sql';

	if(!$sqlfilename || preg_match("/(\.)(exe|jsp|asp|asa|htr|stm|shtml|php3|aspx|cgi|fcgi|pl|php|bat)(\.|$)/i", $sqlfilename)) {
		redirect('您没有输入备份文件名或文件名中使用了敏感的扩展名.', 'cp.php?job=tools&action=backup',5);
	}

	$idstring = '# Identify: '.base64_encode("$timestamp,$SABLOG_VERSION,$volume")."\n";

	//清除表内临时的数据
	$DB->unbuffered_query("TRUNCATE TABLE {$db_prefix}searchindex");

	$sqlcompat = in_array($sqlcompat, array('MYSQL40', 'MYSQL41')) ? $sqlcompat : '';
	$setnames = intval($addsetnames) || ($DB->version() > '4.1' && (!$sqlcompat || $sqlcompat == 'MYSQL41')) ? "SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary;\n\n" : '';

	if($DB->version() > '4.1') {
		$DB->query("SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary;");
		if($sqlcompat == 'MYSQL40') {
			$DB->query("SET SQL_MODE='MYSQL40'");
		}
	}

	$sqldump = '';
	$tableid = $tableid ? $tableid - 1 : 0;
	$startfrom = intval($startfrom);
	for($i = $tableid; $i < count($tables) && strlen($sqldump) < $sizelimit * 1000; $i++) {
		$sqldump .= sqldumptable($tables[$i], $startfrom, strlen($sqldump));
		$startfrom = 0;
	}
	$tableid = $i;
	if(trim($sqldump)) {
		$sqldump = "$idstring".
			"# <?exit();?>\n".
			"# Sablog-X bakfile Multi-Volume Data Dump Vol.$volume\n".
			"# Version: $SABLOG_VERSION\n".
			"# Time: ".sadate('Y-m-d H:i',$timestamp)."\n".
			"# Sablog-X: http://www.sablog.net\n".
			"# --------------------------------------------------------\n\n\n".$setnames.$sqldump;

		if(!writefile($sqlfilename, $sqldump)) {
			redirect('数据文件无法备份到服务器, 请检查目录属性.', 'cp.php?job=tools&action=backup',5);
		} else {
			redirect('分卷备份:数据文件 '.$volume.' 成功创建,程序将自动继续.', "cp.php?job=tools&action=dobackup&filename=".rawurlencode($filename)."&sizelimit=".rawurlencode($sizelimit)."&volume=".rawurlencode($volume)."&tableid=".rawurlencode($tableid)."&startfrom=".rawurlencode($startrow)."&sqlcompat=".rawurlencode($sqlcompat));
		}
	} else {
		redirect('数据成功备份至服务器指定文件中', 'cp.php?job=tools&action=filelist');
	}

}
// 备份操作结束

// 导入RSS
if ($action == 'importrss') {
	$cid = intval($_POST['cid']);
	if (!$cid) {
		redirect('请选择目标分类', 'cp.php?job=tools&action=rssimport');
	}
	$uid = intval($_POST['uid']);
	if (!$uid) {
		redirect('请选择文章作者', 'cp.php?job=tools&action=rssimport');
	}
	$xmlfile = $_FILES['xmlfile'];
	if (is_array($xmlfile)) {
		$attachment      = $xmlfile['tmp_name'];
		$attachment_name = $xmlfile['name'];
		$attachment_size = $xmlfile['size'];
		$attachment_type = $xmlfile['type'];
	}
	if (trim($attachment) != 'none' && trim($attachment) != '' && trim($attachment_name) != '') {
		$rssinfo = pathinfo($attachment_name);
		if ($rssinfo['extension'] == 'xml') {
			$attachment = upfile($attachment, SABLOG_ROOT.'cache/rss_xml_tmp.xml');
			// 如果一种函数上传失败，还可以用其他函数上传
			if (!$attachment) {
				redirect('上传XML文件发生意外错误!');
			}

			$filecontent = loadfile($attachment);

			$rssdata = getrssdata($filecontent);
			$i = 0;
			if (is_array($rssdata)) {
				foreach ($rssdata as $rss) {
					if ($rss['title'] && $rss['dateline'] && $rss['content']) {
						$i++;
						$DB->query("INSERT INTO {$db_prefix}articles (cid, uid, title, content, dateline) VALUES ('$cid', '$uid', '".$rss['title']."', '".$rss['content']."', '".$rss['dateline']."')");
					}
				}
			}
			@unlink($attachment);

			$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles=articles+$i WHERE userid='$uid'");
			$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles=articles+$i WHERE cid='$cid'");
			$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET article_count=article_count+$i");
			archives_recache();
			categories_recache();
			statistics_recache();

			redirect('导入RSS数据成功', 'cp.php?job=article');
		} else {
			redirect('只允许上传XML格式的文件', 'cp.php?job=tools&action=rssimport');
		}
	} else {
		redirect('请选择要上传的XML文件', 'cp.php?job=tools&action=rssimport');
	}
}

if ($action == 'updateall') {
	restats();
	redirect('所有缓存已经更新', 'cp.php?job=tools');
}

// 更新首页统计
if ($action == 'dostatsdata') {
	// 更新首页显示的分类数
	$cate_count = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}categories"), 0);
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET cate_count='$cate_count'");
	// 更新首页显示的文章数
	$article_count = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}articles WHERE visible = '1'"), 0);
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET article_count='$article_count'");
	// 更新首页显示的评论数
	$comment_count = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}comments c LEFT JOIN {$db_prefix}articles a ON (a.articleid=c.articleid) WHERE a.visible='1' AND c.visible='1'"), 0);
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET comment_count='$comment_count'");
	// 更新首页显示的附件数
	$attachment_count = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}attachments aa LEFT JOIN {$db_prefix}articles a ON (a.articleid=aa.articleid) WHERE a.visible='1'"), 0);
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET attachment_count='$attachment_count'");
	// 更新首页显示的Trackback数
	$trackback_count = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}trackbacks t LEFT JOIN {$db_prefix}articles a ON (a.articleid=t.articleid) WHERE a.visible='1' AND t.visible='1'"), 0);
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET trackback_count='$trackback_count'");
	// 更新首页显示的标签(Tags)数
	$tag_count = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}tags"), 0);
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET tag_count='$tag_count'");
	// 更新首页显示的用户数
	$user_count = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}users"), 0);
	$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET user_count='$user_count'");
	statistics_recache();
	redirect('首页统计已经更新', 'cp.php?job=tools&action=rebuild');
}
// 更新所有分类的文章数
if ($action == 'docatedata') {
	$query = $DB->query("SELECT cid, name FROM {$db_prefix}categories");
	while ($cate = $DB->fetch_array($query)) {
		$total = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}articles WHERE visible = '1' AND cid='".$cate['cid']."'"), 0);
		$DB->unbuffered_query("UPDATE {$db_prefix}categories SET articles='$total' WHERE cid='".$cate['cid']."'");
	}
	categories_recache();
	redirect('所有分类的文章数已经更新', 'cp.php?job=tools&action=rebuild');
}
// 重建文章数据
if ($action == 'doarticledata') {
	$step = (!$step) ? 1 : $step;
	$percount = ($percount <= 0) ? 100 : $percount;
	$start    = ($step - 1) * $percount;
	$next     = $start + $percount;
	$step++;
	$jumpurl  = 'cp.php?job=tools&action=doarticledata&step='.$step.'&percount='.$percount;
	$goon     = 0;
	$query = $DB->query("SELECT articleid FROM {$db_prefix}articles ORDER BY articleid LIMIT $start, $percount");
	while ($article = $DB->fetch_array($query)) {
		$goon = 1;
		// 更新所有文章的评论数
		$total = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}comments WHERE articleid='".$article['articleid']."' AND visible='1'"), 0);
		$DB->unbuffered_query("UPDATE {$db_prefix}articles SET comments='$total' WHERE articleid='".$article['articleid']."'");
		// 更新所有文章的Trackback数
		$total = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}trackbacks WHERE visible='1' AND articleid='".$article['articleid']."'"), 0);
		$DB->unbuffered_query("UPDATE {$db_prefix}articles SET trackbacks='$total' WHERE articleid='".$article['articleid']."'");
	}
	if($goon){
		redirect('正在更新 '.$start.' 到 '.$next.' 项', $jumpurl, '2');
	} else{
		$article_count = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}articles WHERE visible = '1'"), 0);
		$DB->unbuffered_query("UPDATE {$db_prefix}statistics SET article_count='$article_count'");
		statistics_recache();
		redirect('成功重建所有文章数据', 'cp.php?job=tools&action=rebuild');
	}
}
// 重建后台用户文章数量
if ($action == 'doadmindata') {
	$query = $DB->query("SELECT userid FROM {$db_prefix}users WHERE groupid='1' OR groupid='2'");
	while ($user = $DB->fetch_array($query)) {
		$total = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}articles WHERE visible='1' AND uid='".$user['userid']."'"), 0);
		$DB->unbuffered_query("UPDATE {$db_prefix}users SET articles='$total' WHERE userid='".$user['userid']."'");
	}
	redirect('成功重建所有后台用户数据', 'cp.php?job=tools&action=rebuild');
}

// 重建附件缩略图
if ($action == 'dothumbdata') {
	require_once(SABLOG_ROOT.'include/func/attachment.func.php');
	$step = (!$step) ? 1 : $step;
	$percount = ($percount <= 0) ? 100 : $percount;
	$start    = ($step - 1) * $percount;
	$next     = $start + $percount;
	$step++;
	$jumpurl  = 'cp.php?job=tools&action=dothumbdata&step='.$step.'&percount='.$percount;
	$goon     = 0;
	$size = explode('x', strtolower($options['attachments_thumbs_size']));

	$attachquery = $DB->query("SELECT * FROM {$db_prefix}attachments WHERE isimage='1' AND thumb_filepath <> '' ORDER BY attachmentid LIMIT $start, $percount");
	while($attach = $DB->fetch_array($attachquery)) {
		$goon = 1;
		if (file_exists(SABLOG_ROOT.$options['attachments_dir'].$attach['thumb_filepath'])) {
			@unlink(SABLOG_ROOT.$options['attachments_dir'].$attach['thumb_filepath']);
			$DB->unbuffered_query("UPDATE {$db_prefix}attachments SET thumb_filepath='', thumb_width='', thumb_height='' WHERE attachmentid='".$attach['attachmentid']."'");
		}
		if (!$options['attachments_thumbs']) {
			$attach_data['thumbwidth']    = '';
			$attach_data['thumbheight']   = '';
			$attach_data['thumbfilepath'] = '';
		} else {
			$extension = getextension($attach['filepath']);
			$attachsubdir = '/date_'.sadate('Ym', $attach['dateline']).'/';
			$thumbname = substr($attach['filepath'],strlen($attachsubdir),32);
			if ($imginfo=@getimagesize(SABLOG_ROOT.$options['attachments_dir'].$attach['filepath'])) {
				if ($imginfo[2]) {
					if (($imginfo[0] > $size[0]) || ($imginfo[1] > $size[1])) {
						$attach_thumb = array(
							'filepath'     => SABLOG_ROOT.$options['attachments_dir'].$attach['filepath'],
							'filename'     => $thumbname,
							'extension'    => $extension,
							'attachsubdir' => $attachsubdir,
							'thumbswidth'  => $size[0],
							'thumbsheight' => $size[1],
						);
						$thumb_data = generate_thumbnail($attach_thumb);
						$attach_data['thumbwidth']    = $thumb_data['thumbwidth'];
						$attach_data['thumbheight']   = $thumb_data['thumbheight'];
						$attach_data['thumbfilepath'] = $attachsubdir.$thumb_data['thumbfilepath'];
					}
				}
			}
		}
		$DB->unbuffered_query("UPDATE {$db_prefix}attachments SET thumb_filepath='".$attach_data['thumbfilepath']."', thumb_width='".$attach_data['thumbwidth']."', thumb_height='".$attach_data['thumbheight']."' WHERE attachmentid='".$attach['attachmentid']."'");
		$article = $DB->fetch_one_array("SELECT attachments FROM {$db_prefix}articles WHERE articleid='".$attach['articleid']."'");
		$attachs = unserialize(sax_stripslashes($article['attachments']));
		@extract($attachs[$attach['attachmentid']]);
		$attachs[$attach['attachmentid']]['thumb_filepath'] = $attach_data['thumbfilepath'];
		$attachs[$attach['attachmentid']]['thumb_width'] = $attach_data['thumbwidth'];
		$attachs[$attach['attachmentid']]['thumb_height'] = $attach_data['thumbheight'];
		$attachs = sax_addslashes(serialize($attachs));
		$DB->unbuffered_query("UPDATE {$db_prefix}articles SET attachments='$attachs' WHERE articleid='".$attach['articleid']."'");

		unset($attach_data);
	}
	if($goon){
		redirect('正在更新 '.$start.' 到 '.$next.' 项', $jumpurl, '2');
	} else{
		redirect('成功重建所有附件缩略图', 'cp.php?job=tools&action=rebuild');
	}
}

//批量删除备份文件
if($action == 'deldbfile') {
    if (!$sqlfile || !is_array($sqlfile)) {
        redirect('未选择任何文件');
    }
	$selected = count($sqlfile);
	$succ = $fail = 0;
    foreach ($sqlfile AS $file=>$value) {
		if (file_exists($file)) {
			@chmod($file, 0777);
			if (@unlink($file)) {
				$succ++;
			} else {
				$fail++;
			}
		} else {
			redirect(basename($file).' 文件已不存在', 'cp.php?job=tools&action=filelist');
		}
    }
    redirect('删除数据文件操作完毕,删除'.$selected.'个,成功'.$succ.'个,失败'.$fail.'个.', 'cp.php?job=tools&action=filelist',5);
}

// 数据库维护操作
if($action == 'dotools') {
	$doname = array(
		'check' => '检查',
		'repair' => '修复',
		'analyze' => '分析',
		'optimize' => '优化'
	);
	$dodb = $tabledb = array();
	foreach ($do as $value) {
		$dodb[] = array('do'=>$value,'name'=>$doname[$value]);
		foreach ($tables AS $table) {
			if ($DB->query($value.' TABLE '.$table)) {
				$result = '<span class="yes">成功</span>';
			} else {
				$result = '<span class="no">失败</span>';
			}
			$tabledb[] = array('do'=>$value,'table'=>$table,'result'=>$result);
		}
	}
	$subnav = '数据库维护';
}// 数据库维护操作结束

if (in_array($action, array('backup', 'tools'))) {
	if ($action == 'backup') {
		$backuppath = sadate('Y-m-d',$timestamp).'_'.random(8);
		$tdtitle = '备份数据库';
		$act = 'dobackup';
	} else {
		$tdtitle = '数据库维护';
		$act = 'dotools';
	}
	$subnav = ''.$tdtitle;
}//backup

// 数据库信息
if ($action == 'mysqlinfo') {
	$mysql_version = mysql_get_server_info();
	$mysql_runtime = '';
	$query = $DB->query("SHOW STATUS");
	while ($r = $DB->fetch_array($query)) {
		if (eregi("^uptime", $r['Variable_name'])){
			$mysql_runtime = $r['Value'];
		}
	}
	$mysql_runtime = format_timespan($mysql_runtime);

	$query = $DB->query("SHOW TABLE STATUS");
	$sablog_table_num = $sablog_table_rows = $sablog_data_size = $sablog_index_size = $sablog_free_size = 0;
	$other_table_num = $other_table_rows = $other_data_size = $other_index_size = $other_free_size = 0;
	$sablog_table = $other_table = array();
	while($table = $DB->fetch_array($query)) {
		if(in_array($table['Name'],$tables)) {
			$sablog_data_size = $sablog_data_size + $table['Data_length'];
			$sablog_index_size = $sablog_index_size + $table['Index_length'];
			$sablog_table_rows = $sablog_table_rows + $table['Rows'];
			$sablog_free_size = $sablog_free_size + $table['Data_free'];
			$table['Create_time'] = $table['Create_time'] ? $table['Create_time'] : 'Unknow';
			$table['Update_time'] = $table['Update_time'] ? $table['Update_time'] : 'Unknow';
			$table['Data_length'] = get_real_size($table['Data_length']);
			$table['Index_length'] = get_real_size($table['Index_length']);
			$table['Data_free'] = get_real_size($table['Data_free']);
			$sablog_table_num++;
			$sablog_table[] = $table;
		} else {
			$other_data_size = $other_data_size + $table['Data_length'];
			$other_index_size = $other_index_size + $table['Index_length'];
			$other_table_rows = $other_table_rows + $table['Rows'];
			$other_free_size = $other_free_size + $table['Data_free'];
			$table['Create_time'] = $table['Create_time'] ? $table['Create_time'] : 'Unknow';
			$table['Update_time'] = $table['Update_time'] ? $table['Update_time'] : 'Unknow';
			$table['Data_length'] = get_real_size($table['Data_length']);
			$table['Index_length'] = get_real_size($table['Index_length']);
			$table['Data_free'] = get_real_size($table['Data_free']);
			$other_table_num++;
			$other_table[] = $table;
		}
	}
	$sablog_data_size = get_real_size($sablog_data_size);
	$sablog_index_size = get_real_size($sablog_index_size);
	$sablog_free_size = get_real_size($sablog_free_size);
	$other_data_size = get_real_size($other_data_size);
	$other_index_size = get_real_size($other_index_size);
	$other_free_size = get_real_size($other_free_size);
	unset($table);
	$subnav = '数据库信息';
}

// 管理数据文件
if ($action == 'filelist') {
	$file_i = 0;
	if(is_dir($backupdir)) {
		$dirs = dir($backupdir);
		$dbfiles = array();
		$today = @sadate('Y-m-d',$timestamp);
		require_once(SABLOG_ROOT.'include/func/attachment.func.php');
		while ($file = $dirs->read()) {
			$filepath = SABLOG_ROOT.$backupdir.'/'.$file;
			$pathinfo = pathinfo($file);
			if(is_file($filepath) && $pathinfo['extension'] == 'sql') {
				$identify = explode(',', base64_decode(preg_replace("/^# Identify:\s*(\w+).*/s", "\\1", loadfile($filepath, 200))));
				$moday = @sadate('Y-m-d',@filemtime($filepath));
				$mtime = @sadate('Y-m-d H:i',@filemtime($filepath));
				$dbfile = array(
					'filesize' => sizecount(filesize($filepath)),
					'mtime' => ($moday == $today) ? '<font color="#FF0000">'.$mtime.'</font>' : $mtime,
					'bktime' => $identify[0] ? @sadate('Y-m-d H:i',$identify[0]) : '未知',
					'version' => $identify[1] ? $identify[1] : '未知',
					'volume' => $identify[2] ? $identify[2] : '未知',
					'filepath' => urlencode($file),
					'filename' => htmlspecialchars($file),
				);
				$file_i++;
				$dbfiles[] = $dbfile;
			}
		}
		unset($dbfile);
		$dirs->close();
		$noexists = 0;
	} else {
		$noexists = 1;
	}
	$subnav = '数据文件管理';
} // end filelist

if ($action == 'checkresume' && $dbimport) {
	$subnav = '导入备份数据';
	$sqlfile = htmlspecialchars($sqlfile);
	$identify = explode(',', base64_decode(preg_replace("/^# Identify:\s*(\w+).*/s", "\\1", loadfile(SABLOG_ROOT.$backupdir.'/'.$sqlfile, 200))));
	if (count($identify) != 3) {
		redirect('SQL文件有可能是当前程序的老版本备份的,为了程序程序正常运作,不允许导入.确实要导入,请通过其他MYSQL管理程序导入.', 'cp.php?job=tools&action=filelist',5);
	}
	if ($identify[2] != 1) {
		redirect('为了程序正常运作,只允许导入卷号为1的SQL文件.', 'cp.php?job=tools&action=filelist',5);
	}
	if ($identify[1] != $SABLOG_VERSION) {
		redirect('SQL文件版本信息和当前程序版本不匹配,为了程序程序正常运作,不允许导入.确实要导入,请通过其他MYSQL管理程序导入.', 'cp.php?job=tools&action=filelist',5);
	}
}//backup

if ($action == 'rssimport') {
	$subnav = '导入RSS数据';
	$catedb = array();
	$query = $DB->query("SELECT cid,name FROM {$db_prefix}categories ORDER BY displayorder");
	while ($cate = $DB->fetch_array($query)) {
		$catedb[] = $cate;
	}
	unset($cate);

	$query = $DB->query("SELECT userid,username FROM {$db_prefix}users WHERE groupid='1' OR groupid='2' ORDER BY userid");
	$userdb = array();
	while ($user = $DB->fetch_array($query)) {
		$userdb[] = $user;
	}
	unset($user);
	$DB->free_result($query);
}//backup

if($action == 'cache') {
	require_once(SABLOG_ROOT.'include/func/attachment.func.php');
	$cachedesc = array(
		'archives'	  => '日志归档',
		'categories'  => '日志分类',
		'hottags'     => '热门标签',
		'links'		  => '友情链接',
		'newcomments' => '最新评论',
		'settings'    => '系统参数',
		'statistics'  => '统计信息',
		'stylevars'   => '模板变量',
		'latestpub'   => '最新发布'
	);
	$cachedb = array();
	foreach ($cachedesc AS $name => $desc)	{
		$filepath = SABLOG_ROOT.'cache/cache_'.$name.'.php';
		if(is_file($filepath)) {
			$cachefile['name'] = $name;
			$cachefile['desc'] = $desc;
			$cachefile['size'] = sizecount(filesize($filepath));
			$cachefile['mtime'] = @sadate('Y-m-d H:i',@filemtime($filepath));
			$bakinfo = loadfile($filepath, 200);
			$detail=explode("\n",$bakinfo);
			$cachefile['ctime'] = (strlen($detail[2]) == 33) ? substr($detail[2],13,16) : '未知';
			$cachedb[] = $cachefile;
		}
	}
	unset($cachefile);
	$subnav = '缓存管理';
}

// 重建数据
if($action == 'rebuild') {
	$subnav = '重建数据';
}//rebuild

// 搜索记录
if($action == 'searchlog') {
	if($page) {
		$start_limit = ($page - 1) * 30;
	} else {
		$start_limit = 0;
		$page = 1;
	}
	$total = $DB->result($DB->query("SELECT COUNT(*) FROM {$db_prefix}searchindex"), 0);
	$multipage = multi($tatol, 30, $page, "admincp.php?job=cache&action=searchlog");
	$searchdb = array();
	$query = $DB->query("SELECT * FROM {$db_prefix}searchindex ORDER BY searchid DESC LIMIT $start_limit, 30");
	while ($search = $DB->fetch_array($query)) {
		$search['dateline'] = sadate('Y-m-d H:i',$search['dateline']);
		$searchdb[] = $search;
	}//end while
	unset($search);
	$DB->free_result($query);
	$subnav = '搜索记录';
}

// 运行记录
if (in_array($action, array('adminlog', 'loginlog', 'deladminlog', 'delloginlog', 'dberrorlog', 'deldberrorlog'))) {
	if (in_array($action, array('adminlog', 'deladminlog'))) {
		$logsfile = 'adminlog';
		$opname = '后台操作记录';
	} elseif (in_array($action, array('loginlog', 'delloginlog'))) {
		$logsfile = 'loginlog';
		$opname = '后台登陆记录';
	} elseif (in_array($action, array('dberrorlog', 'deldberrorlog'))) {
		$logsfile = 'dberrorlog';
		$opname = '数据库出错记录';
	}
	if (in_array($action, array('deladminlog', 'delloginlog', 'deldberrorlog'))) {
		$logfilename = SABLOG_ROOT.'cache/log/'.$logsfile.'.php';
		if(file_exists($logfilename)){
			$logfile = @file($logfilename);
		} else{
			$logfile=array();
		}
		$logs = array();
		if(is_array($logfile)) {
			foreach($logfile as $log) {
				$logs[] = $log;
			}
		}
		$logs = @array_reverse($logs);
		$total = count($logs);
		if ($total>100) {
			$output=@array_slice($logs,0,100);
			$output=@array_reverse($output);
			$output=@implode("",$output);

			@touch($logfilename);
			@$fp=fopen($logfilename,'rb+');
			@flock($fp,LOCK_EX);
			@fwrite($fp,$output);
			@ftruncate($fp,strlen($output));
			@fclose($fp);
			@chmod($filename,0777);

			redirect('多余的'.$opname.'已成功删除', 'cp.php?job=tools&action='.$logsfile);
		} else {
			redirect('记录少于100条不允许删除', 'cp.php?job=tools&action='.$logsfile);
		}
	}//removelog

	//管理日志页面
	if (in_array($action, array('adminlog', 'loginlog', 'dberrorlog'))) {
		@$logfile = file(SABLOG_ROOT.'cache/log/'.$logsfile.'.php');
		$logs = $logdb = array();
		if(is_array($logfile)) {
			foreach($logfile as $log) {
				$logs[] = $log;
			}
		}
		$logs = @array_reverse($logs);
		$pagenum = 20;
		if($page) {
			$start_limit = ($page - 1) * $pagenum;
		} else {
			$start_limit = 0;
			$page = 1;
		}
		$total = count($logs);
		if ($total) {
			$multipage = multi($total, $pagenum, $page, 'cp.php?job=tools&action='.$logsfile);
			for($i = 0; $i < $start_limit; $i++) {
				unset($logs[$i]);
			}
			for($i = $start_limit + $pagenum; $i < $total; $i++) {
				unset($logs[$i]);
			}
			if ($action == 'adminlog') {
				foreach($logs as $logrow) {
					$logrow = explode("\t", $logrow);
					$logrow[1] = sadate('Y-m-d H:i:s', $logrow[1]);
					$logdb[] = $logrow;
				}
			} elseif ($action == 'loginlog') {
				foreach($logs as $logrow) {
					$logrow = explode("\t", $logrow);
					$logrow[1] = $logrow[1] ? htmlspecialchars($logrow[1]) : '<span class="no">Null</span>';
					$logrow[2] = sadate('Y-m-d H:i:s', $logrow[2]);
					$logrow[4] = trim($logrow[4]) == 'Succeed' ? '<span class="yes">Succeed</span>' : '<span class="no">Failed</span>';
					$logdb[] = $logrow;
				}
			} else {
				foreach($logs as $logrow) {
					$logrow = explode("\t", $logrow);
					$logrow[1] = sadate('Y-m-d H:i:s', $logrow[1]);
					$logdb[] = $logrow;
				}
			}
		}
		$subnav = $opname;
		unset($logrow);
	}//end
}

$navlink_L = ' &raquo; <a href="cp.php?job=tools">系统维护</a>'.($subnav ? ' &raquo; '.$subnav : '');
cpheader($subnav);
include template('tools');
?>